package com.gensdai.leliang.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.ActivityApplyList;
import com.gensdai.leliang.activity.ActivityCollctionList;
import com.gensdai.leliang.activity.Binding;
import com.gensdai.leliang.activity.Delivery_address;
import com.gensdai.leliang.activity.Indent;
import com.gensdai.leliang.activity.Invite_friend;
import com.gensdai.leliang.activity.LoginDeal;
import com.gensdai.leliang.activity.Set_Mm;
import com.gensdai.leliang.activity.Touch_we;
import com.gensdai.leliang.activity.UserCenter;
import com.gensdai.leliang.activity.UserNews;
import com.gensdai.leliang.activity.my_wallet;
import com.gensdai.leliang.activity.user_enter;
import com.gensdai.leliang.base.BaseFragment;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 首页 我的  fragment
 * Created by liutao on 2017/5/23.
 */

public class FragmentMyCard extends BaseFragment implements View.OnClickListener {

    //    @BindView(R.id.username)
//    AppCompatEditText username;
//    @BindView(R.id.pass)
//    EditText pass;
    @BindView(R.id.head_portrait) // 头像点击登录
            ImageView head_portrait;
    @BindView(R.id.go_my_wallet)
    LinearLayout goMyWallet; // 我的钱包
    @BindView(R.id.invite_friend)
    LinearLayout inviteFriend; //  邀请好友
    @BindView(R.id.delivery_address)
    LinearLayout deliveryAddress; // 收货地址
    @BindView(R.id.set_mm)
    LinearLayout setMm; //修改密码
    @BindView(R.id.touch_we)
    LinearLayout touchWe; //联系我们
    @BindView(R.id.bang_zfb)
    LinearLayout bangZfb;

    Unbinder unbinder;
    @BindView(R.id.indent)// 全部订单
            LinearLayout indent;
    @BindView(R.id.payment) //待付款
            LinearLayout payment;
    @BindView(R.id.shipments) //待发货
            LinearLayout shipments;
    @BindView(R.id.for_receiving)//待收货
            LinearLayout forReceiving;
    @BindView(R.id.evaluate) // 待评价
            LinearLayout evaluate;
    @BindView(R.id.name) // 昵称
            TextView name;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.usertype)
    TextView usertype; // 会员类型
    @BindView(R.id.payment1)
    TextView payment1;
    @BindView(R.id.shipments2)
    TextView shipments2;
    @BindView(R.id.for_receiving3)
    TextView forReceiving3;
    @BindView(R.id.for_evaluate4)
    TextView forEvaluate4;
    @BindView(R.id.go_my_collect)//我的收藏
            LinearLayout goMyCollect;
    @BindView(R.id.refund)
    TextView refund;
    @BindView(R.id.for_refund)
    LinearLayout forRefund;
    @BindView(R.id.regard_group)
    LinearLayout regardGroup;// 关于集团
    @BindView(R.id.geshu)
    TextView geshu;
    @BindView(R.id.hyjs)
    ImageView hyjs;

    SharedPreferences share;
    SharedPreferences.Editor ed;

    private final int ENTER = 1;//
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    try {
                        int i = 0;
                        if (new json_base().GOOD((String) msg.obj)) {
                            String[] list = (String[]) new json_base().JsonCall(new JSONObject((String) msg.obj));
                            i = Integer.parseInt(list[0]) + Integer.parseInt(list[1]);
                            if (i > 0) {
                                if (i > 99) {
                                    geshu.setText("99+");
                                } else {
                                    geshu.setText(i + "");
                                }
                                geshu.setVisibility(View.VISIBLE);
                            } else {
                                geshu.setVisibility(View.INVISIBLE);
                            }
                        } else {
                        }
                        ed.putString("newsCall", i + "");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    ed.commit();
                    break;
                default:
                    break;
            }
        }
    };


    public static FragmentMyCard NewInstance() {

        return new FragmentMyCard();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my, container, false);
        unbinder = ButterKnife.bind(this, v);
        init();
        return v;

    }

    @OnClick(R.id.messagebox)
    public void onMessageClick(View v) {
        if (share.getBoolean("enter_state", false)) {
            Intent go_usercenter = new Intent(getActivity(), UserNews.class);
            startActivity(go_usercenter);
        } else {
            startActivity(new Intent(getActivity(), UserNews.class));
        }
    }

    @OnClick(R.id.for_refund)
    public void onRefundClick(View v) {
        if (share.getBoolean("enter_state", false)) {
            Intent go_usercenter = new Intent(getActivity(), ActivityApplyList.class);
            startActivity(go_usercenter);
        } else {
            startActivity(new Intent(getActivity(), user_enter.class));
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Query();
        share = getActivity().getSharedPreferences("User", Context.MODE_PRIVATE);
        ed = share.edit();
        String memberType = share.getString("memberType", "");
        String daifuNum = share.getString("daifuNum", "0"); //代付款提示
        String daifaNum = share.getString("daifaNum", "0"); //待发货提示
        String daishouNum = share.getString("daishouNum", "0");//待收货提示
        String daipinglun = share.getString("waitComment", "0");//待评价提示
        String name = share.getString("user_name", "");
        String level = share.getString("level", "");

        if (!share.getString("img", "").equals("")) {
            Uri uri = Uri.parse(share.getString("img", ""));
            head_portrait.setImageURI(uri);
        }
        if (name.equals("")) {
            if (share.getString("phone", "").equalsIgnoreCase("")) {
                this.name.setText("尚未登陆");
            } else {
                this.name.setText(share.getString("phone", ""));
            }
        } else {
            this.name.setText(name);
            Log.e("this.name.setText();", name);
        }


        if (memberType.equals("1")) {
            switch (level) {
                case "0":
                    usertype.setText("内部会员");
                    break;
                case "10":
                    usertype.setText("区域经理");
                    break;
                case "20":
                    usertype.setText("加盟合作商");
                    break;
                case "30":
                    usertype.setText("社交分享商");
                    break;
                case "40":
                    usertype.setText("业务经理");
                    break;
                default:
                    usertype.setText("内部会员");
                    break;
            }
        } else if (memberType.equals("2")) {
            usertype.setText("分享会员");
        } else {
            usertype.setVisibility(View.INVISIBLE);
        }

        if (Integer.parseInt(daifuNum) > 0) { // 代付款
            payment1.setText(daifuNum);
            payment1.setVisibility(View.VISIBLE);
        } else {
            payment1.setText(daifuNum);
            payment1.setVisibility(View.GONE);
        }
        if (Integer.parseInt(daifaNum) > 0) { //待发货
            shipments2.setText(daifaNum);
            shipments2.setVisibility(View.VISIBLE);
        } else {
            shipments2.setText(daifaNum);
            shipments2.setVisibility(View.GONE);
        }
        if (Integer.parseInt(daishouNum) > 0) { // 待收货
            forReceiving3.setText(daishouNum);
            forReceiving3.setVisibility(View.VISIBLE);
        } else {
            forReceiving3.setText(daishouNum);
            forReceiving3.setVisibility(View.GONE);
        }
        if (Integer.parseInt(daipinglun) > 0) { // 待评论
            forEvaluate4.setText(daipinglun);
            forEvaluate4.setVisibility(View.VISIBLE);
        } else {
            forEvaluate4.setText(daipinglun);
            forEvaluate4.setVisibility(View.GONE);
        }


        //权限控制  0：无权限、1：有权限
        String myWallet = share.getString("myWallet", "0");
        String bindAlipay = share.getString("bindAlipay", "0");
        String contactUs = share.getString("contactUs", "0");
        String receiveAddress = share.getString("receiveAddress", "0");
        String changePassword = share.getString("changePassword", "0");
        String inviteFriends = share.getString("inviteFriends", "0");
        String myCollection = share.getString("myCollection", "0");

        if (TextUtils.equals("1", myWallet)) {
            goMyWallet.setVisibility(View.VISIBLE);
        } else {
            goMyWallet.setVisibility(View.GONE);
        }

        if (TextUtils.equals("1", bindAlipay)) {
            bangZfb.setVisibility(View.VISIBLE);
        } else {
            bangZfb.setVisibility(View.GONE);
        }
        if (TextUtils.equals("1", contactUs)) {
            touchWe.setVisibility(View.VISIBLE);
        } else {
            touchWe.setVisibility(View.GONE);
        }
        if (TextUtils.equals("1", receiveAddress)) {
            deliveryAddress.setVisibility(View.VISIBLE);
        } else {
            deliveryAddress.setVisibility(View.GONE);
        }
        if (TextUtils.equals("1", changePassword)) {
            setMm.setVisibility(View.VISIBLE);
        } else {
            setMm.setVisibility(View.GONE);
        }
        if (TextUtils.equals("1", inviteFriends)) {
            inviteFriend.setVisibility(View.VISIBLE);
        } else {
            inviteFriend.setVisibility(View.GONE);
        }
        if (TextUtils.equals("1", myCollection)) {
            goMyCollect.setVisibility(View.VISIBLE);
        } else {
            goMyCollect.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        hyjs.setVisibility(View.GONE);
    }

    /**
     * 初始化
     */
    private void init() {
        share = getActivity().getSharedPreferences("User", Context.MODE_PRIVATE);


        goMyWallet.setOnClickListener(this);
        head_portrait.setOnClickListener(this);
        inviteFriend.setOnClickListener(this);
        indent.setOnClickListener(this);
        payment.setOnClickListener(this);
        shipments.setOnClickListener(this);
        deliveryAddress.setOnClickListener(this);
        forReceiving.setOnClickListener(this);
        setMm.setOnClickListener(this);
        touchWe.setOnClickListener(this);
        bangZfb.setOnClickListener(this);
        evaluate.setOnClickListener(this);
        goMyCollect.setOnClickListener(this);
        usertype.setOnClickListener(this);
        regardGroup.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_my_wallet:
                Intent go_my_wallet = new Intent(getActivity(), my_wallet.class);
                startActivity(go_my_wallet);
                break;
            case R.id.regard_group:
                Intent go_regard_group = new Intent(getActivity(), LoginDeal.class);
                go_regard_group.putExtra("title","关于集团");
                go_regard_group.putExtra("type","1");
                startActivity(go_regard_group);
                break;
            case R.id.head_portrait:
                if (share.getBoolean("enter_state", false)) {
                    Intent go_usercenter = new Intent(getActivity(), UserCenter.class);
                    startActivity(go_usercenter);
                } else {
                    goEnter();
                }
                break;
            case R.id.invite_friend:
                Intent go_invite_friend = new Intent(getActivity(), Invite_friend.class);
                startActivity(go_invite_friend);
                break;
            case R.id.delivery_address:
                Intent go_delivery_address = new Intent(getActivity(), Delivery_address.class);
                startActivity(go_delivery_address);

//                Intent go_delivery_address = new Intent(getActivity(), AddressListActivity.class);
//                startActivity(go_delivery_address);

            case R.id.usertype:
                if (hyjs.getVisibility() == View.GONE) {
                    String memberType = share.getString("memberType", "");
                    String level = share.getString("level", "");
                    if (memberType.equals("1")) {
                        switch (level) {
                            case "0":
                                hyjs.setBackground(getActivity().getResources().getDrawable(R.mipmap.nbhy));
                                usertype.setText("内部会员");
                                break;
                            case "10":
                                hyjs.setBackground(getActivity().getResources().getDrawable(R.mipmap.qyjl));
                                usertype.setText("区域经理");
                                break;
                            case "20":
                                hyjs.setBackground(getActivity().getResources().getDrawable(R.mipmap.jms));
                                usertype.setText("加盟合作商");
                                break;
                            case "30":
                                hyjs.setBackground(getActivity().getResources().getDrawable(R.mipmap.sjfxs));
                                usertype.setText("社交分享商");
                                break;
                            case "40":
                                hyjs.setBackground(getActivity().getResources().getDrawable(R.mipmap.ywjl));
                                usertype.setText("业务经理");
                                break;
                            default:
                                usertype.setText("内部会员");
                                break;
                        }
                        hyjs.setVisibility(View.VISIBLE);
                    } else if (memberType.equals("2")) {
                        usertype.setText("分享会员");
                        hyjs.setVisibility(View.VISIBLE);
                    }
                } else {
                    hyjs.setVisibility(View.GONE);
                }

                break;
            case R.id.set_mm:
//                Toast.makeText(getActivity(), "功能正在开发中，尽请关注哦！~", Toast.LENGTH_SHORT).show();
                Intent go_set_mm = new Intent(getActivity(), Set_Mm.class);
                startActivity(go_set_mm);
                break;
            case R.id.touch_we:
                Intent go_touch_we = new Intent(getActivity(), Touch_we.class);
                startActivity(go_touch_we);
                break;
            case R.id.bang_zfb:
                Intent go_bang_zfb = new Intent(getActivity(), Binding.class);
                startActivity(go_bang_zfb);
                break;
            case R.id.go_my_collect:
                Intent go_bang_sc = new Intent(getActivity(), ActivityCollctionList.class);
                startActivity(go_bang_sc);
                break;
            case R.id.indent:
                Go_User_Indent("0");
                break;
            case R.id.payment:
                Go_User_Indent("1");
                break;
            case R.id.shipments:
                Go_User_Indent("2");
                break;
            case R.id.for_receiving:
                Go_User_Indent("3");
                break;
            case R.id.evaluate:
                Go_User_Indent("4");
                break;
            default:
                break;
        }
    }

    private void Go_User_Indent(String state) {
        Intent go_Indent = new Intent(getActivity(), Indent.class);
        go_Indent.putExtra("state", state);
        startActivity(go_Indent);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

//        //可以用原本点击处理
//        RxView.clicks(head_portrait).throttleFirst(500, TimeUnit.MILLISECONDS).subscribe(new Observer<Object>() {
//            @Override
//            public void onSubscribe(@NonNull Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(@NonNull Object o) {
//                System.out.println("点击按钮处理");
//                goenter();
////                httpRegister();
//            }
//
//            @Override
//            public void onError(@NonNull Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });

    }

    /**
     * 前往登录界面
     */
    private void goEnter() {
        Intent user_go_enter = new Intent(getActivity(), user_enter.class);
        startActivity(user_go_enter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    /**
     * 查询消息
     */
    private void Query() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", share.getString("userno", ""));
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        ApiService.getInstance(getActivity()).CQUERY_MESSAGE_COUNT_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        try {
                            int i = 0;
                            if (new json_base().GOOD(s)) {
                                String[] list = (String[]) new json_base().JsonCall(new JSONObject(s));
                                i = Integer.parseInt(list[0]) + Integer.parseInt(list[1]);
                                if (i > 0) {
                                    if (i > 99) {
                                        geshu.setText("99+");
                                    } else {
                                        geshu.setText(i + "");
                                    }
                                    geshu.setVisibility(View.VISIBLE);
                                } else {
                                    geshu.setVisibility(View.INVISIBLE);
                                }
                            } else {
                            }
                            ed.putString("newsCall", i + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        ed.commit();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


}
